import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { maService } from '../../../../service/ma/ma.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {insService} from "../../../../service/ins/ins.service";
import {ProductService} from "../../../../service/prod/product.service";
import {fileService} from "../../../../service/file/file.service";

@Component({
  selector: 'file-view-edit',
  templateUrl: './file-edit.component.html',
  styleUrls: ['./file-edit.component.less']
})
export class fileViewEdit1Component implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    bpmStatus:"10",
    fxjOut11: null,
    fxjOut12: '已归还',
    fxjOut13: null,
    fxjOut14: null,
    fxjOut15: null,
    fxjOut16: null,
    fxjOut17: null,
    fxjOut18: null,
    fxjOut19: null,
    fxjOut20: null
  };
  bpmStatus =  [{text: '我的', value: '1'}, {text: '已归还', value: '10'}, {text: '未归还', value: '20'}];

  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;

  uploadUrl = '';
  sysusers=[];
  avatarParam = { sbtype: 'No',  filetype:'file',orderNo: 'no'};
  fileList = [];
  avatarUrl:string;
  loading = false;


  constructor(
    private productService: ProductService,

    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private fileService: fileService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {

    this.loadsysusers();

    this.uploadUrl = this.fileService.uploadUrl();

    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"]
      console.log("this.product.id****************"+this.product.id);
      // 获取商品详情
      this.getProductInfo();
      // this.getfileList(this.product.id);

    });
    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 1000);
  }

  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }



  getProductInfo() {
    this.fileService.getfile1(this.product.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;
      console.log(this.product);
      this.product.fxjOut12="已归还";
      this.avatarParam = { sbtype: 'No',  filetype:'file',orderNo: this.product.fileNo};
      this.titleService.setTitle("编辑");
      if (data.data.fxjFileListList.length > 0) {
        let flag = 0;
        for (const detail of data.data.fxjFileListList) {
          this.fileList.push( {
            uid: flag,
            name: detail.fileName,
            status: 'done',
            url: detail.fileUrl,
            id: detail.id
          } )
          flag++;
        }
      };
    })
  }

  back() {
    this.router.navigate(['/file/file/1']);
  }

  save() {
    if(this.product.fxjOut17===''||this.product.fxjOut17===null){
      this.msg.warning("请选择归还时间");
      return;
    }
    let fxjFileMainPage = {
      updateBy:this.setting.user.username,
      bpmStatus:"10",
      id:this.product.id,
      fxjOut11: this.product.fxjOut11,
      fxjOut12: this.product.fxjOut12,
      fxjOut13: this.product.fxjOut13,
      fxjOut14: this.product.fxjOut14,
      fxjOut15: this.product.fxjOut15, /*No show*/
      fxjOut16: this.product.fxjOut16,
      fxjOut17: this.product.fxjOut17,
      fxjOut18: this.product.fxjOut18
      // fiOperDate: this.product.fiOperDate /*No show*/
    };
    console.log(fxjFileMainPage)
    // 调用接口
    this.fileService.editfile1(fxjFileMainPage).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.msg.success('修改成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
        setTimeout(() => {
          this.back();
        }, 100);
      } else {
        this.msg.error(data['message']);
      }
    })
  }
  // 加载证件类型
  loadsysusers() {
    this.sysusers = [];
    this.comm.getsysusers(this.setting.user.sysorgCode).subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.sysusers.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  // 图片 wuwq
  upLoadChange(event) {
    console.log(event);
    let file = event ? event.file : null;
    console.log(file);
    let datas = file && file.id ? file : file.response;
    console.log(datas);
    if (datas) {
        if (event.type == 'success') {
            console.log('ss');
        } else if (event.type == 'removed') {
          console.log('aa');
          let picId = file.id ? file.id : file.response[0].fileId
          this.delPic(picId);
        }
    }
  }


  // 删除图片 wuwq
  delPic(id) {
    this.fileService.delfile(id).pipe(
        catchError(err => {
          return of(err);
        })
      ).subscribe(data => {
        if(data.ok){
          // this.productorder = data.data;
          // console.log(this.productorder);
          // this.reload();
        }else{
          console.log("22")
        }
      })
  }


}
